package com.cloudcc.cloudframe.net.async;

import org.apache.http.Header;

import android.text.TextUtils;

import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.ServerStatusCode;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.NumberUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.loopj.android.http.TextHttpResponseHandler;

/**
 * 最好使用 jsonRequest 代替 提示语句改变成 服务器 来处理
 * 
 * @Description: TODO()
 * @author wangzhiqiang
 * @date 2015-11-24 下午1:56:36
 * 
 */
@Deprecated
public abstract class MyJsonHttpResponseHandler extends TextHttpResponseHandler
		implements ServerStatusCode {

	@Override
	public void onSuccess(int statusCode, Header[] headers,
			String responseString) {
		if (TextUtils.isEmpty(responseString)) {
			handleFailure(new ErrorInfo(NET_DATA_EXCEPTION));
			return;
		}
		LogUtils.d("net", "网络请求数据" + responseString);
		JsonParser parser = new JsonParser();
		boolean result = false;
		int retrunCode = -1000;
		String returnInfo = "";
		JsonObject root = null;
		try {
			root = parser.parse(responseString).getAsJsonObject();
			result = root.get("result").getAsBoolean();
			retrunCode = NumberUtils.toInt(
					root.get("returnCode").getAsString(), -1000);
			returnInfo = root.get("returnInfo").getAsString();
		} catch (JsonSyntaxException e) {
			handleFailure(new ErrorInfo(JSON_PARSER_ERROR));
			return;
		} catch (NullPointerException e) {
			handleFailure(new ErrorInfo(JSON_PARSER_ERROR));
			return;
		}
		if (result && retrunCode == SUCCESS_OK) {
			handleSuccess(root, responseString);
		} else {
			handleFailure(new ErrorInfo(retrunCode, "网络通信失败..."));
		}

	}

	@Override
	public void onFailure(int statusCode, Header[] headers,
			String responseString, Throwable throwable) {
		if (throwable != null && StringUtils.isNotBlank(throwable.getMessage())) {
			LogUtils.e("net", throwable.getMessage());
		}
		// 处理检测问题
		if (statusCode == NET_INTERCEPTOR && throwable != null) {
			int errorCode = NumberUtils.toInt(throwable.getMessage(), -100);
			if (errorCode != -100) {
				handleFailure(ErrorInfo.get(errorCode));
			} else {
				handleFailure(new ErrorInfo(NET_DATA_EXCEPTION));
			}
		} else {
			handleFailure(new ErrorInfo(NET_DATA_EXCEPTION));
		}

	}

	/**
	 * 处理 自定义json
	 * 
	 * @param resp
	 */
	public abstract void handleSuccess(JsonObject json, String resp);

	/**
	 * 处理 失败
	 * 
	 * @param e
	 */
	public abstract void handleFailure(ErrorInfo e);

}
